package com.token.service.impl;

import com.token.mapper.SysRoleMapper;
import com.token.mapper.SysUserMapper;
import com.token.model.po.SysRole;
import com.token.model.po.SysUser;
import com.token.service.TransactionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.transaction.support.TransactionTemplate;

import org.springframework.transaction.support.TransactionCallback;


import javax.annotation.Resource;

/**
 * @auther: henriy
 * @Date: 2024/2/22
 */
@Slf4j
@Service
public class TransactionServiceImpl implements TransactionService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysRoleMapper sysRoleMapper;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Override
    public void addTransaction() {
        transactionTemplate.execute((TransactionCallback<Void>) status -> {
            try {
                SysUser sysUser = new SysUser();
                sysUser.setId(5L);
                sysUser.setSex(1);
                sysUserMapper.insert(sysUser);

                // 此处会发生异常，roleCode字段为必传项，事务发生回滚
                SysRole sysRole = new SysRole();
                sysRole.setId(5L);
                sysRole.setRoleName("role_code");
                sysRoleMapper.insert(sysRole);
                return null;
            } catch (Exception e) {
                // 方式一
                status.setRollbackOnly();
                // 方式二：手动回滚事务
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw e;
            }
        });
    }

}
